package com.summer.framework.common.distributed.lock;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * @auther: 杨杰
 * @date: 2019/6/13 17:35
 * @description: Redisson分布式读写锁的实现类
 */
@Configuration
@Slf4j
public class DistributedReadWriteLockHandle implements DistributedReadWriteLock {

    @Autowired
    private RedissonClient redisson;

    @Override
    public <T> T read(DistributedLockCallback<T> callback) {
        RReadWriteLock readWriteLock = redisson.getReadWriteLock(callback.getLockName());
        readWriteLock.readLock().lock();
        try {
            return callback.process();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

    @Override
    public <T> T write(DistributedLockCallback<T> callback) {
        RReadWriteLock readWriteLock = redisson.getReadWriteLock(callback.getLockName());
        readWriteLock.writeLock().lock();
        try {
            return callback.process();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

}
